package com.cnap.multiclouldmgmt.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.cnap.multiclouldmgmt.repository.cnap", sqlSessionFactoryRef = "msvcSqlSessionFactory")
public class MicroSvcDataSourceConfig {

    @Bean(name = "msvcDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.cnap")
    public DataSource getDateSourceApm() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "msvcSqlSessionFactory")
    public SqlSessionFactory apmSqlSessionFactory(@Qualifier("msvcDataSource") DataSource datasource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/cnap/*.xml"));
        return bean.getObject();
    }

    @Bean("msvcSqlSessionTemplate")
    public SqlSessionTemplate apmSqlSessionTemplate(
            @Qualifier("msvcSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }

    @Bean(name = "msvcDataSourceInitializer")
    public DataSourceInitializer dataSourceInitializer(@Qualifier("msvcDataSource") DataSource dataSource) {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(new ClassPathResource("db/cnap-schema.sql"));
        //resourceDatabasePopulator.addScript(new ClassPathResource("db/master-data-prod.sql"));
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
        return dataSourceInitializer;
    }
}
